import pandas as pd
import numpy as np
from config import Config
import os

def get_popular_products(products, n=10):
    """获取热门商品"""
    # 综合评分 = 0.4 * 标准化销量 + 0.3 * 评分 + 0.2 * 是否新品 + 0.1 * 价格倒置
    products = products.copy()

    # 标准化
    products['sales_norm'] = (products['sales'] - products['sales'].min()) / \
                             (products['sales'].max() - products['sales'].min())
    products['price_norm'] = 1 - (products['price'] - products['price'].min()) / \
                             (products['price'].max() - products['price'].min())

    # 计算综合分数
    products['popularity_score'] = (
            0.4 * products['sales_norm'] +
            0.3 * (products['rating'] / 5) +
            0.2 * products['is_new'].astype(int) +
            0.1 * products['price_norm']
    )

    return products.nlargest(n, 'popularity_score')


def prepare_for_serving():
    """准备服务所需数据"""
    # 确保所有必要文件存在
    required_files = [
        Config.HYBRID_MODEL_FILE,
        Config.INTERACTION_MATRIX_FILE,
        os.path.join(Config.PROCESSED_DATA_DIR, "user_id_map.pkl"),
        os.path.join(Config.PROCESSED_DATA_DIR, "item_id_map.pkl"),
        Config.USERS_FILE,
        Config.PRODUCTS_FILE
    ]

    for file in required_files:
        if not os.path.exists(file):
            raise FileNotFoundError(f"Required file not found: {file}")

    # 加载商品数据用于展示
    products = pd.read_csv(Config.PRODUCTS_FILE)
    return products